package com.tanhua.server.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.commons.utils.Constants;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.PeachblossomVoice;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.VoiceVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.service.PeachblossomVoiceApi;
import com.tanhua.service.UserInfoApi;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author げっしょく
 * @date 2021/11/7
 */
@Service
public class PeachblossomService {

    @DubboReference
    private PeachblossomVoiceApi peachblossomVoiceApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public VoiceVo randomVoice() {
        String key = Constants.USER_GETVOICE_COUNT + UserHolder.getId();
        //查询该用户在redis中是否存在
        Boolean aBoolean = redisTemplate.hasKey(key);
        if (!aBoolean) {
            Integer count = 10;
            Long time = getNowToNextDaySeconds();
            redisTemplate.opsForValue().set(key, count.toString(), time, TimeUnit.SECONDS);
        }
        //通过redis查询还有多少查询次数
        String s = redisTemplate.opsForValue().get(key);
        Integer count = Integer.parseInt(s);
        if (count <= 0) {
            //次数不足, 抛出异常
            throw new BusinessException(ErrorResult.getVoiceError());
        }
        //随机获取一条语音
        PeachblossomVoice p = peachblossomVoiceApi.randomVoice();
        if (p == null) {
            throw new BusinessException(ErrorResult.noAudioError());
        }
        //通过发布语音的id查询数据库
        Long userId = p.getUserId();
        UserInfo userInfo = userInfoApi.getUserById(userId);
        //封装数据类型
        count = count-1;
        VoiceVo vo = VoiceVo.init(userInfo, p, count);
        //改变reids中存储的数据
        redisTemplate.opsForValue().set(key, count.toString());
        return vo;
    }

    //获取当前时间与第二天零点的秒差
    public Long getNowToNextDaySeconds() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_YEAR, 1);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        long l1 = System.currentTimeMillis();
        //获得离第二天凌晨还有多少秒    1秒= 1000毫秒
        return  (cal.getTimeInMillis() - System.currentTimeMillis()) / 1000;
    }

    public void saveVoice(MultipartFile soundFile) throws IOException {
        //获取文件名的后缀
        String fileName = soundFile.getOriginalFilename();
        String substring = fileName.substring(fileName.lastIndexOf(".") + 1);
        //上传音频到FastDFS
        StorePath storePath = client.uploadFile(soundFile.getInputStream(), soundFile.getSize(), substring, null);
        //获取音频的访问地址
        String voiceUrl = webServer.getWebServerUrl() + storePath.getFullPath();
        PeachblossomVoice p = new PeachblossomVoice();
        p.setCreated(System.currentTimeMillis());
        p.setUserId(UserHolder.getId());
        p.setVoiceUrl(voiceUrl);
        //保存数据库
        peachblossomVoiceApi.saveVoice(p);

    }
}
